package cn.picclife.mwx.common.web.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.picclife.mwx.common.core.util.JsonUtils;
import org.apache.commons.lang3.StringUtils;

public class CorsUtil {
	public boolean isPreflight(ServletRequest request) {
		boolean retVal = false;
		HttpServletRequest req = (HttpServletRequest) request;
		String method = req.getMethod();//获取请求方式
		String origin = req.getHeader("origin");//用于说明请求从那发起，而且只用于post请求
		String controlReqMethod = req.getHeader("access-control-request-method");
		if ("OPTIONS".equals(method) && StringUtils.isNotEmpty(origin) && StringUtils.isNotEmpty(controlReqMethod)) {
			retVal = true;
			// Ulog.debug("====tl this is preflight request:" + retVal);
		}
		// Ulog.debug("====tl http request method:" + method);
		// Ulog.debug("====tl http request origin:" + origin);
		// Ulog.debug("====tl http controlReqMethod:" + controlReqMethod);
		// Ulog.debug("====tl is preflight ? : " + retVal);
		return retVal;
	}

	private void setCorsHeader(ServletResponse response, String key, String value) {
		HttpServletResponse res = (HttpServletResponse) response;
//		if (StringUtils.isEmpty(res.getHeader(key))) {
			res.setHeader(key, value);
//		} else {
//			// Ulog.debug("===tl why the cors header is not null?" + key + ":" +
//			// value);
//		}
	}

	/**
	 * 设置preflight,actual request公共权限
	 * 
	 * @param request
	 * @param response
	 */
	private void allowCommonPermit(ServletRequest request, ServletResponse response) {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		String origin = req.getHeader("Origin");
		String origin1 = req.getHeader("origin");
		//this.setCorsHeader(res, "Access-Control-Allow-Origin", req.getHeader("Origin"));=========================================自己修改
		this.setCorsHeader(res, "Access-Control-Allow-Origin", "*");
		this.setCorsHeader(res, "Access-Control-Allow-Credentials", "true");
		// 防止代理服务器比如nginx缓存origin
		this.setCorsHeader(res, "Vary", "origin");

	}

	/**
	 * 设置preflight request权限  预检查请求
	 * 
	 * @param request
	 * @param response
	 */
	public void allowPreflightPermit(ServletRequest request, ServletResponse response) {
		HttpServletResponse res = (HttpServletResponse) response;
		// 设置公共权限
		this.allowCommonPermit(request, response);
		// 设置allow headers(如果接口有自定义的header参数请在此增加),若此属性不设置则当有自定义参数的请求将不被允许。
		this.setCorsHeader(res, "Access-Control-Allow-Headers",
				"DNT,x-auth-token,rqstSource,X-CustomHeader,Keep-Alive,User-Agent,"
				+ "X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,ASEKEY,TOKEN,TIME_STAMP,MD5_TOKEN,SYSTEM_CODE");
		// 设置preflight结果缓存时间(chrome允许可设置的最长不超过5分钟,firefox不超过24小时),此属性可减少客户端浏览器的preflight请求次数从而提高效率。
		this.setCorsHeader(res, "Access-Control-Max-Age", "300");
		//this.setCorsHeader(res, "Access-Control-Allow-Origin", "*");//=========================自己添加
	}

	/**
	 * 设置actual request权限   实际请求
	 * 
	 * @param request
	 * @param response
	 */
	public void allowActualPermit(ServletRequest request, ServletResponse response) {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		Cookie[] cookies = req.getCookies();
		if (cookies == null) {
//			Ulog.warn("===tl:cookies is null " + "of the request url:" + req.getRequestURL());
		} else {
			// for (Cookie cookie : cookies) {
			// Ulog.debug("===tl cookie:" + cookie.getName() + ":" +
			// cookie.getValue() + " of the request url:" +
			// req.getRequestURL());
			// }
		}

		this.allowCommonPermit(request, response);
		// 返回授权的http expose
		// header(如果接口中返回的有自定义的header参数请在此增加),若此参数不设置则服务端自定义的属性在客户端不可见。
		this.setCorsHeader(res, "Access-ControlExpose-Headers",
				"DNT,x-auth-token,rqstSource,X-CustomHeader,"
				+ "Keep-Alive,User-Agent,X-Requested-With,"
				+ "If-Modified-Since,Cache-Control,Content-Type,ASEKEY,TOKEN,TIME_STAMP,MD5_TOKEN,SYSTEM_CODE");//====================隋哥

	}

}
